package cdu.sl.service.impl;

import cdu.sl.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;

@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;

    /**
     * 生成6位随机验证码
     */
    @Override
    public String generateVerificationCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    /**
     * 发送验证码邮件
     * @param toEmail 目标邮箱
     * @return 验证码
     */
    @Override
    public String sendVerificationCode(String toEmail) {
        String verificationCode = generateVerificationCode();
        
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromEmail);
        message.setTo(toEmail);
        message.setSubject("Flashcards App - 验证码");
        message.setText("您的验证码是: " + verificationCode + "\n验证码有效期为5分钟。");
        
        try {
            mailSender.send(message);
            log.info("验证码邮件已发送至: {}", toEmail);
            return verificationCode;
        } catch (Exception e) {
            log.error("发送验证码邮件失败: {}", e.getMessage());
            throw new RuntimeException("发送验证码邮件失败");
        }
    }




} 